Completed
Push — master ( 605e3d...3de0bb )
by Muhammad Dyas
14s queued 13s
created

task.ts ➔ createTask   A

Complexity

Conditions 2

Size

Total Lines 31
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 31
rs 9.256
c 0
b 0
f 0
cc 2
1
import {CloudTasksClient} from '@google-cloud/tasks';
2
import {google} from '@google-cloud/tasks/build/protos/protos';
3
import {PollForm, TaskEvent} from './interfaces';
4
5
const client = new CloudTasksClient();
6
7
export async function createTask(payload: string, scheduleInSeconds: number) {
8
  const project = process.env.GCP_PROJECT;
9
  const queue = process.env.QUEUE_NAME;
10
  const location = process.env.FUNCTION_REGION;
11
  if (!project || !queue || !location) {
12
    throw new Error('Missing required environment variables');
13
  }
14
  const url = `https://${location}-${project}.cloudfunctions.net/app`;
15
  // Construct the fully qualified queue name.
16
  const parent = client.queuePath(project, location, queue);
17
18
  const task: google.cloud.tasks.v2.ITask = {
19
    httpRequest: {
20
      headers: {
21
        'Content-Type': 'application/json', // Set content type to ensure compatibility your application's request parsing
22
      }, httpMethod: 'POST', url,
23
    },
24
  };
25
26
  task.httpRequest!.body = Buffer.from(payload).toString('base64');
27
28
  // The time when the task is scheduled to be attempted.
29
  task.scheduleTime = {
30
    seconds: scheduleInSeconds / 1000,
31
  };
32
33
  const request: google.cloud.tasks.v2.ICreateTaskRequest = {parent: parent, task: task};
34
  const [response] = await client.createTask(request);
35
  console.log(`Created task ${response.name}`);
36
  return response;
37
}
38
39
export async function createAutoCloseTask(config: PollForm, messageId: string) {
40
  if (config.autoClose && config.closedTime) {
41
    const taskPayload: TaskEvent = {'id': messageId, 'action': 'close_poll', 'type': 'TASK'};
42
    await createTask(JSON.stringify(taskPayload), config.closedTime);
43
    if (config.autoMention) {
44
      const taskPayload: TaskEvent = {'id': messageId, 'action': 'remind_all', 'type': 'TASK'};
45
      await createTask(JSON.stringify(taskPayload), config.closedTime - 420000);
46
    }
47
  }
48
}
49